var express = require('express');
var router = express.Router();

var childProcess = require('child_process');
var fs = require('fs');
var path = require('path');
var chokidar = require('chokidar');

router.post('/projects/qam', function(req, res, next) {
    var data = req.body.data;
    var args = [];
    for (var item in data) {
        args.push(data[item]);
    }
    var images = [];
    var watcher = chokidar.watch(path.join(__dirname, '../public/image'), {
        persistent: true
    });
    watcher.on('change', function(watchPath) {
        var serverPath = req.protocol + '://' + req.get('host');
        var fileName = watchPath.split('/').pop();
        images.push(serverPath + '/image/ofdm/' fileName);
    });
    fs.chmod(path.join(__dirname, '../public/ofdm.m'), 0777, (err)=>{
        if (err) {
            console.log(err);
        }
    });
    childProcess.exec('octave ' + path.join(__dirname, '../public/ofdm.m'), [],
        (err, stdout, stderr) => {
            // stdout 取决于octave程序除了绘图外是否还有输出，如误码率
            res.json({
                data: {
                    imgPath: images
                }
            })
        }
    );
});

module.exports = router;
